const config = require('../../util/config')
const logger = require('log4js').getLogger()

async function getRedirectLink(obj) {
    const {
        Network,
        Page,
        DOM,
        Runtime,
        Emulation
    } = this.client;
    obj = obj || {}
    if (!obj.link) {
        return new Promise((resolve, reject) => {
            reject('系统错误')
        })
    }
    obj.times = (obj.times || 0) + 1
    if (obj.step !== 0) {
        logger.debug('[' + __filename + ':' + __line + ']', 'getting redirect link', JSON.stringify(obj))
        obj.step = 0
    }
    if (obj.test && obj.test(obj.link)) {
        return Promise.resolve(result.value)
    }
    var { result } = await Runtime.evaluate({ expression: 'location.href' })
    obj.oldLink = result.value
    try {
        Page.navigate({
            url: obj.link
        })
        return step1.call(this, obj)
    } catch (err) {
        logger.error('[' + __filename + ':' + __line + ']', err)
    }
}

async function step1(obj) {
    const {
        Network,
        Page,
        DOM,
        Runtime,
        Emulation
    } = this.client;
    ++obj.times
    if (obj.times > config.chromeMaxTimes) {
        Page.navigate({
                url: 'https://www.baidu.com/'
            })
            // return new Promise((resolve, reject) => {
            //     reject('获取跳转链接超时')
            // })
        var { result } = await Runtime.evaluate({ expression: 'location.href' })
        return Promise.resolve(result.value)
    }
    if (obj.step !== 1) {
        logger.debug('[' + __filename + ':' + __line + ']', 'getting redirect link step 1', JSON.stringify(obj))
        obj.step = 1
    }
    var { result } = await Runtime.evaluate({ expression: 'location.href' })
    if (result.value.startsWith('https://uland.taobao.com/coupon/edetail?')) {
        var { result } = await Runtime.evaluate({ expression: 'document.querySelectorAll(".item-wrap a").length' })
        if (result.value != '0') {
            await Runtime.evaluate({ expression: 'document.querySelectorAll(".item-wrap a")[0].click()' })
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    step1.call(this, obj).then(result => {
                        resolve(result)
                    }, result => {
                        reject(result)
                    })
                }, 1000)
            })
        }
    }
    var { result } = await Runtime.evaluate({ expression: 'location.href' })
    if (result.value == obj.oldLink || result.value == obj.link) {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                step1.call(this, obj).then(result => {
                    resolve(result)
                }, result => {
                    reject(result)
                })
            }, 1000)
        })
    }
    if (obj.test && obj.test(result.value)) {
        Page.navigate({
            url: 'https://www.baidu.com/'
        })
        return Promise.resolve(result.value)
    }
    if (result.value != obj.redirectLink) {
        obj.redirectLink = result.value
        logger.debug('[' + __filename + ':' + __line + ']', 'getting redirect link step 1', JSON.stringify(obj))
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                step1.call(this, obj).then(result => {
                    resolve(result)
                }, result => {
                    reject(result)
                })
            }, 1000)
        })
    }
    if (obj.test && !obj.test(result.value)) {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                step1.call(this, obj).then(result => {
                    resolve(result)
                }, result => {
                    reject(result)
                })
            }, 1000)
        })
    }
    Page.navigate({
        url: 'https://www.baidu.com/'
    })
    return Promise.resolve(result.value)
}

module.exports = getRedirectLink